local os = require("os")
local inifile = require("inifile")
local socket = require("socket")  --调用socket包

local config_file = arg[1]
local init_config = inifile.parse(config_file)
local local_path = init_config["RSYNC_CLIENT"]["RSYNC_CLIENT_LOCAL_PATH"]
local remote_module = init_config["RSYNC_SERVER"]["RSYNC_SERVER_MODULE"]
local passwd_path = init_config["RSYNC_CLIENT"]["RSYNC_CLIENT_PASSWD_PATH"]
local rsync_user = init_config["RSYNC_CLIENT"]["RSYNC_CLIENT_USERNAME"]

if #local_path < 1 then
    return
end
--lua的TCP通信发送字符串末尾必须添加\n
--client
local ip = init_config["RSYNC_CLIENT"]["RSYNC_CLIENT_REQUEST_IP"]    --程序设置要了解的server端的ip地址
local port = init_config["RSYNC_CLIENT"]["RSYNC_CLIENT_REQUEST_PORT"] --设置端口
 
-- 连接前先全量同步一次
total_sync_cmd = string.format("rsync -avzcR --delete --password-file=%s %s@%s::%s %s", passwd_path, rsync_user, ip, remote_module, local_path)
print(total_sync_cmd)
local res = os.execute(total_sync_cmd)

local client = assert(socket.connect(ip, port))    --根据上边的参数连接server端，若未连接上直接报错

-- 12小时全量同步一次
check_interval = 12 * 60 * 60
client:settimeout(check_interval)
while 1 do
    local s, status, partial = client:receive()    --等待服务器发送过来的信号
    print(s, status, partial)
    if status == "closed" then 
        break
    end
    if status == "timeout" then
        print(total_sync_cmd)
        os.execute(total_sync_cmd)
    else
        local run_cmd = string.format(s, passwd_path, rsync_user, ip, local_path)
        print(run_cmd)
        os.execute(run_cmd)
    end
end
 
client:close()